<template>
  <div>
    <AForm :model="searchFrom" class="erp-search-form">
      <ARow class="grid-demo" :gutter="10">
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <ARangePicker
              v-model="searchFrom.deliveryDate"
              value-format="YYYY-MM-DD"
              :placeholder="['送货日期', '送货日期']"
            />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <AInput v-model="searchFrom.customerName" placeholder="客户名" />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <AInput v-model="searchFrom.materialName" placeholder="产品名称" />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <ASelect v-model="searchFrom.isInclTax" placeholder="是否含税" allow-clear>
              <AOption label="是" :value="1"></AOption>
              <AOption label="否" :value="0"></AOption>
            </ASelect>
          </AFormItem>
        </ACol>
      </ARow>
    </AForm>
    <ACard>
      <div class="erp-mb-10 w100 erp-search-btn-box">
        <ASpace>
          <AButton type="primary" @click="onSearch">
            <template #icon>
              <icon-search />
            </template>
          </AButton>
          <ATooltip content="清空筛选项" position="top">
            <AButton type="dashed" @click="onReset">
              <template #icon>
                <icon-refresh />
              </template>
            </AButton>
          </ATooltip>
          <AButton v-if="isAuth([1, 2])" type="outline" @click="openEdit('新增')">新增</AButton>
          <ATooltip
            v-if="isAuth([1, 2])"
            content="请选择未出库的数据"
            :disabled="!isEmpty(selectRows)"
          >
            <AButton
              type="outline"
              :disabled="isEmpty(selectRows)"
              :loading="outWarehouseLoad"
              @click="outWarehouse()"
            >
              出库
            </AButton>
          </ATooltip>
          <!-- <AButton type="outline" status="normal">生成采购单</AButton>
          <AButton type="outline" status="normal">生成生产单</AButton> -->
        </ASpace>
        <ASpace>
          <AButton type="primary" :loading="exportLoad" @click="onExport('table')">导出</AButton>
        </ASpace>
      </div>
      <ATable
        ref="tableRef"
        :pagination="false"
        :data="tableData"
        :bordered="{ cell: true }"
        column-resizable
        size="small"
        :scroll="tableScroll"
        span-all
        scrollbar
        :row-selection="{ showCheckedAll: true, type: 'checkbox' }"
        :span-method="spanMethod"
        row-key="deliveryOrderDetailId"
        @select="
          (rowKeys: (string | number)[], rowKey: string | number, record: TableData) =>
            tableEvent('select', { rowKeys, rowKey, record })
        "
        @select-all="(checked: boolean) => tableEvent('select-all', checked)"
      >
        <template #columns>
          <ATableColumn title="单号" data-index="deliveryOrderCode" :width="100">
            <template #cell="{ record }">
              <ATooltip
                :disabled="record.detailList.every((item) => item.outboundStatus)"
                content="当前订单有产品没有出库"
              >
                <div
                  :style="{
                    color: record.detailList.every((item) => item.outboundStatus) ? '' : 'orange'
                  }"
                >
                  {{ record.deliveryOrderCode }}
                </div>
              </ATooltip>
            </template>
          </ATableColumn>
          <ATableColumn title="送货日期" data-index="deliveryDate" :width="100">
            <template #cell="{ record }">
              <div v-if="record.deliveryDate">
                {{ dayjs(record.deliveryDate).format('YYYY-MM-DD') }}
              </div>
            </template>
          </ATableColumn>
          <ATableColumn title="客户名称" data-index="customerName" :width="100"></ATableColumn>
          <ATableColumn title="产品名称" data-index="materialName" :width="100"></ATableColumn>
          <ATableColumn title="规格型号" data-index="spec" :width="100"></ATableColumn>
          <ATableColumn title="单位" data-index="unit" :width="100"></ATableColumn>
          <ATableColumn title="数量" data-index="qty" :width="100"></ATableColumn>
          <ATableColumn title="单价" data-index="unitPrice" :width="100"></ATableColumn>
          <ATableColumn title="金额" data-index="amt" :width="100">
            <template #cell="{ record }">
              {{ formatPrice(decimalRound(record.qty! * record.unitPrice!, 4)) }}
            </template>
          </ATableColumn>
          <ATableColumn title="出库" data-index="outboundStatus" :width="70" align="center">
            <template #cell="{ record }">
              <icon-check-circle-fill
                v-if="record.outboundStatus"
                style="color: #67c23a"
                size="20px"
              />
              <icon-close-circle-fill
                v-if="!record.outboundStatus"
                style="color: red"
                size="20px"
              />
            </template>
          </ATableColumn>
          <ATableColumn title="总金额" data-index="totalAmt" :width="100">
            <template #cell="{ record }">
              {{ formatPrice(decimalRound(sumAmt(record), 4)) }}
            </template>
          </ATableColumn>
          <ATableColumn title="含税" data-index="isInclTax" :width="70" align="center">
            <template #cell="{ record }">
              <icon-check-circle-fill v-if="record.isInclTax" style="color: #67c23a" size="20px" />
              <icon-close-circle-fill v-if="!record.isInclTax" style="color: red" size="20px" />
            </template>
          </ATableColumn>
          <ATableColumn title="业务员" data-index="sellersName" :width="100"></ATableColumn>
          <ATableColumn title="运输车辆" data-index="transportCarNo" :width="100"></ATableColumn>
          <ATableColumn title="附件" data-index="fileList" :width="100" align="center">
            <template #cell="{ record }">
              <ADropdown
                v-if="!isEmpty(record.fileList)"
                @select="(fileUrl: any) => openFlie(record, fileUrl)"
              >
                <ALink>{{ record.fileList.length }}</ALink>
                <template #content>
                  <ADoption
                    v-for="(item, index) in record.fileList"
                    :key="index"
                    :value="item.fileUrl"
                  >
                    {{ item.fileName }}
                  </ADoption>
                </template>
              </ADropdown>
            </template>
          </ATableColumn>
          <ATableColumn title="开票情况" data-index="invoiceStatus" :width="100"></ATableColumn>
          <ATableColumn title="是否作废" data-index="isVoid" :width="100">
            <template #cell="{ record }">
              {{ record.isVoid ? '是' : '否' }}
            </template>
          </ATableColumn>
          <ATableColumn title="备注" data-index="remark" :width="100"></ATableColumn>
          <ATableColumn v-if="isAuth([1, 2])" title="操作" :width="150" fixed="right">
            <template #cell="{ record }">
              <ASpace>
                <AButton type="primary" size="mini" @click="rowEvent(record, 'edit')">
                  修改
                </AButton>
                <AButton type="primary" size="mini" @click="rowEvent(record, 'print')">
                  打印
                </AButton>
              </ASpace>
              <ASpace class="erp-mt-6">
                <AButton status="danger" size="mini" @click="rowEvent(record, 'del')">
                  作废
                </AButton>
              </ASpace>
            </template>
          </ATableColumn>
        </template>
      </ATable>
      <div class="arco-table-pagination">
        <APagination
          :total="pageParam.totalCount"
          :page-size="pageParam.pageSize"
          show-total
          @change="(page: number) => tableEvent('page-change', page)"
        />
      </div>
    </ACard>
    <EditPopupForm
      v-model:visible="editModal"
      :title="editModalTitle"
      :check-data="rowData"
      @reload="
        () => {
          getTableData()
          clearTableSelect()
        }
      "
    ></EditPopupForm>
    <deliveryBillPrint ref="deliveryBillPrintRef" :check-data="detailData"></deliveryBillPrint>
  </div>
</template>

<script lang="ts" setup>
import {
  batchOutWarehouseDelivery,
  DeliveryListSearch,
  deliveryOrderVoid,
  DeliveryResHanldeItem,
  DeliveryResItem,
  getDeliveryAllList,
  getDeliveryDetail,
  getDeliveryPageList,
  outWarehouseDelivery
} from '@renderer/api/logisticsDep'
import EditPopupForm from './editPopupForm.vue'
import deliveryBillPrint from './print.vue'
import { Message, Modal, TableData, TableInstance } from '@arco-design/web-vue'
import dayjs from 'dayjs'
import { isEmpty, sum, sumBy } from 'lodash-es'
import { decimalRound, formatPrice, downloadByteFile } from '@renderer/utils/mixins'
import { isAuth } from '@renderer/utils/auth'

const detailData = ref<DeliveryResItem>({
  deliveryOrderId: '',
  deliveryOrderCode: '',
  customerId: '',
  customerName: '',
  deliveryDate: '',
  isInclTax: 0,
  transportCarNo: '',
  invoiceStatus: '',
  remark: '',
  detailList: [],
  createdBy: '',
  createdDt: '',
  updatedBy: '',
  updatedDt: '',
  fileList: [],
  deliveryMethod: '',
  contactName: '',
  customerAddress: '',
  contactPhone: '',
  sellersName: '',
  sellersId: ''
}) // 打印数据
const searchFrom = ref<DeliveryListSearch>({})
const editModal = ref(false)
const editModalTitle = ref('新增')
const tableData = ref<DeliveryResHanldeItem[]>([])
const pageParam = reactive({
  currentPage: 1,
  pageSize: 20,
  totalCount: 0
})
const deliveryBillPrintRef = ref<InstanceType<typeof deliveryBillPrint>>() // 打印组件
const selectRows = ref<DeliveryResHanldeItem[]>([])
const outWarehouseLoad = ref(false)
const { width, height } = useWindowSize()
const tableScroll = ref({ x: width.value, y: height.value - 320 })
const tableRef = ref<TableInstance>()

onMounted(() => {
  getTableData()
})

function sumAmt(rowData: DeliveryResItem) {
  const amts = rowData.detailList.map((item) =>
    Number(decimalRound(item.qty! * item.unitPrice!, 4))
  )
  return sum(amts)
}

function clearTableSelect() {
  tableRef.value?.selectAll(false)
  selectRows.value = []
}

function formatData(baseData: DeliveryResItem[]): DeliveryResHanldeItem[] {
  return baseData
    .map((item) => {
      if (!isEmpty(item.detailList)) {
        return item.detailList.map((detailItem, index) => {
          if (index === 0) {
            return {
              ...detailItem,
              ...item,
              span: item.detailList.length,
              totalAmt: decimalRound(sumBy(item.detailList, 'amt'), 4)
            }
          } else {
            return { ...detailItem, ...item }
          }
        })
      } else {
        return [item] as DeliveryResHanldeItem[]
      }
    })
    .flat()
}

async function getTableData() {
  const [deliveryStartDate, deliveryEndDate] = searchFrom.value.deliveryDate! || []
  searchFrom.value.deliveryEndDate = deliveryEndDate
  searchFrom.value.deliveryStartDate = deliveryStartDate
  const res = await getDeliveryPageList({ ...searchFrom.value, ...pageParam })
  tableData.value = formatData(res.data.list)
  pageParam.totalCount = res.data.totalCount!
}

const onSearch = () => {
  pageParam.currentPage = 1
  getTableData()
}

function onReset() {
  searchFrom.value = {}
  pageParam.currentPage = 1
  pageParam.pageSize = 20
  getTableData()
}

const spanMethod = ({ record, columnIndex }) => {
  if (columnIndex < 4 || columnIndex > 9) {
    if (record.span) {
      return {
        colspan: 1,
        rowspan: record.span
      }
    }
  }
}

function tableEvent(type: 'page-change' | 'select' | 'select-all', param: any) {
  switch (type) {
    case 'page-change':
      pageParam.currentPage = param
      getTableData()
      break
    case 'select':
      {
        const { rowKeys, rowKey, record } = param
        if (rowKeys.includes(rowKey)) {
          if (!record.outboundStatus) {
            const temp = record.detailList.map((item) => {
              item.customerId = record.customerId
              return item
            })
            selectRows.value = selectRows.value?.concat(temp)
          }
        } else {
          selectRows.value = selectRows.value.filter(
            (item) => item.deliveryOrderDetailId != record.deliveryOrderDetailId
          )
        }
      }
      break
    case 'select-all':
      if (param) {
        selectRows.value = selectRows.value.concat(tableData.value)
      } else {
        const ids = tableData.value.map((item) => item.deliveryOrderDetailId)
        selectRows.value = selectRows.value.filter(
          (item) => !ids.includes(item.deliveryOrderDetailId)
        )
      }
      break

    default:
      break
  }
}

function openEdit(title: string) {
  editModalTitle.value = title
  editModal.value = true
}

async function outWarehouseApi() {
  outWarehouseLoad.value = true
  const reqParam: outWarehouseDelivery[] = selectRows.value.map((item) => {
    return {
      materialStockId: item.materialStockId!,
      stockQty: item.qty || 0,
      deliveryOrderDetailId: item.deliveryOrderDetailId!
    }
  })
  await batchOutWarehouseDelivery(reqParam)
  getTableData()
  Message.success('出库成功')
  outWarehouseLoad.value = false
}

function outWarehouse() {
  if (isEmpty(selectRows.value)) return
  outWarehouseApi()
}

const rowData = ref({})

function rowEvent(row: DeliveryResItem, type: 'del' | 'copy' | 'edit' | 'print') {
  switch (type) {
    case 'del':
      Modal.warning({
        title: '警告',
        content: '当前数据作废后不可恢复，是否继续？',
        okText: '确认',
        cancelText: '取消',
        simple: false,
        hideCancel: false,
        maskClosable: false,
        closable: false,
        onOk: () => {
          deliveryOrderVoid({ deliveryOrderId: row.deliveryOrderId! }).then(() => {
            Message.success('作废成功')
            getTableData()
          })
        },
        onCancel: () => {}
      })
      break
    case 'copy':
      rowData.value = row
      editModalTitle.value = '新增'
      editModal.value = true
      break
    case 'edit':
      rowData.value = row
      editModalTitle.value = '修改'
      editModal.value = true
      break
    case 'print':
      getDeliveryDetail({ deliveryOrderId: row.deliveryOrderId! }).then((res) => {
        detailData.value = res.data
        nextTick(() => {
          deliveryBillPrintRef.value?.printInfo()
        })
      })
      break

    default:
      break
  }
}

const openFlie = (record: DeliveryResHanldeItem, flieUrl: string) => {
  const temp = record.fileList?.find((item) => item.fileUrl === flieUrl)
  if (temp) {
    downloadByteFile(temp)
  }
}

const exportLoad = ref(false)

async function onExport(type: 'table' | 'template') {
  let fileTitle: string
  exportLoad.value = true
  const headerData = [
    { title: '单号', value: 'deliveryOrderCode', width: 180 },
    { title: '送货日期', value: 'deliveryDate', width: 180 },
    { title: '客户名称', value: 'customerName' },
    { title: '产品名称', value: 'materialName' },
    { title: '规格型号', value: 'spec' },
    { title: '单位', value: 'unit' },
    { title: '数量', value: 'qty' },
    { title: '单价', value: 'unitPrice' },
    { title: '金额', value: 'amt' },
    { title: '出库', value: 'outboundStatus' },
    { title: '含税', value: 'isInclTax' },
    { title: '业务员', value: 'sellersName' },
    { title: '运输车辆', value: 'transportCarNo' },
    { title: '回单', value: 'attachFiles' },
    { title: '开票情况', value: 'invoiceStatus' },
    { title: '销售订单', value: 'orderCode' },
    { title: '备注', value: 'remark' }
  ]
  let excelData: DeliveryResHanldeItem[] = []
  switch (type) {
    case 'table':
      {
        fileTitle = '送货明细数据'
        headerData.unshift({ title: '序号', value: 'index', width: 80 })
        const res = await getDeliveryAllList(searchFrom.value)
        excelData = formatData(res.data.list).map((item, index) => {
          item.index = index + 1
          item.deliveryDate = item.deliveryDate ? dayjs(item.deliveryDate).format('YYYY-MM-DD') : ''
          item.isInclTax = item.isInclTax ? '是' : '否'
          item.outboundStatus = item.isInclTax ? '是' : '否'
          item.attachFiles = item.fileList?.map((item) => item.fileUrl)
          item.amt = decimalRound(item.qty! * item.unitPrice!, 4) as number
          return item
        })
      }
      break
    default:
      break
  }
  import('@renderer/utils/vendor').then((excel) => {
    excel.exportExcel(excelData, headerData, fileTitle)
    exportLoad.value = false
  })
}
</script>
<style lang="less" scoped>
.erp-search-btn-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
